package com.example.capsule_chat0322.fragment;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentResultListener;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.capsule_chat0322.R;
import com.example.capsule_chat0322.activity.FriendMoreFunctionActivity;
import com.example.capsule_chat0322.activity.OneToOneChatActivity;
import com.example.capsule_chat0322.adapter.FriendListAdapter;
import com.example.capsule_chat0322.adapter.FriendMoreFunctionAdapter;
import com.example.capsule_chat0322.bean.FriendApplyBean;
import com.example.capsule_chat0322.bean.FunctionBean;
import com.example.capsule_chat0322.bean.UserInfoBean;
import com.example.capsule_chat0322.connect.ServerOperation;
import com.example.capsule_chat0322.global.GlobalAssistMap;
import com.example.capsule_chat0322.interfaces.FriendItemOnClickInterface;
import com.example.capsule_chat0322.request.FriendRequest;

import java.util.List;
import java.util.concurrent.CompletableFuture;


/**
 * @Author zhuzhiming
 * @Date 2022/5/1 14:11
 */
public class FriendListFragment extends Fragment {

    private List<UserInfoBean> friendBeanList;
    private RecyclerView friend_recycler_view;
    private FriendListAdapter friendListAdapter;
    private static boolean isFirst = true;
    private TextView friend_info;
    private TextView friend_list_more;
    private ImageView remind;
    private static final int UPDATE_Friend_CODE = 3;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getParentFragmentManager().setFragmentResultListener("skipToChatRoomListMark", this, new FragmentResultListener() {
            @Override
            public void onFragmentResult(@NonNull String requestKey, @NonNull Bundle bundle) {
                String result = bundle.getString("isSkip");
                if (result != null) {
                    isFirst = false;
                }
            }
        });

        Bundle result = new Bundle();
        result.putString("isSkip", "true");
        getParentFragmentManager().setFragmentResult("skipToChatRoomListMark", result);

    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = View.inflate(getActivity(), R.layout.friend_list, null);
        initView(view);//初始化UI控件
        return view;
    }


    public void initView(View view)  {

        friend_recycler_view = view.findViewById(R.id.friend_recycler_view);
        friend_info = view.findViewById(R.id.friend_info);
        friend_list_more = view.findViewById(R.id.friend_list_more);
        remind = view.findViewById(R.id.remind);

        GlobalAssistMap.putObject("friendListFragment",FriendListFragment.this);

        GlobalAssistMap.putObject("remind",remind);

        GlobalAssistMap.putObject("friendRecyclerView", friend_recycler_view);

        String userId = (String) GlobalAssistMap.getObject("userId");

        if (userId == null) {
            try {
                Thread.sleep(100);
                userId = (String) GlobalAssistMap.getObject("userId");
                if (userId == null) {
                    Thread.sleep(100);
                    userId = (String) GlobalAssistMap.getObject("userId");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }


        if (userId == null) {
            return;
        }

        FriendRequest.getFriendFunctionList(new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(@NonNull Message message) {

                List<FunctionBean> functionBeans = (List<FunctionBean>) message.obj;

                FriendMoreFunctionAdapter adapter = new FriendMoreFunctionAdapter(functionBeans);
                GlobalAssistMap.putObject("friendMoreFunctionAdapter", adapter);

                for (FunctionBean functionBean : functionBeans) {
                    if (functionBean.getFunctionName().equals("好友申请")) {
                        List<FriendApplyBean> applyList = functionBean.getApplyList();
                        GlobalAssistMap.putObject("applyList",applyList);
                        if (applyList != null && applyList.size() > 0) {
                            remind.setVisibility(View.VISIBLE);
                        } else {
                            remind.setVisibility(View.GONE);
                        }
                    }
                }

                return true;
            }
        }), userId);


        friend_list_more.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.setClass(getActivity(), FriendMoreFunctionActivity.class);
                remind.setVisibility(View.GONE);
                startActivityForResult(intent, UPDATE_Friend_CODE);
            }
        });
        getFriendList();
    }

    private void getFriendList() {

        this.friendBeanList = (List<UserInfoBean>) GlobalAssistMap.getObject("friends");

        if (friendBeanList == null) {

            String userId = (String) GlobalAssistMap.getObject("userId");

            FriendRequest.doGetUserFriend(new Handler(new Handler.Callback() {
                @RequiresApi(api = Build.VERSION_CODES.N)
                @Override
                public boolean handleMessage(@NonNull Message message) {
                    friendBeanList = (List<UserInfoBean>) message.obj;

                    GlobalAssistMap.putObject("friends", friendBeanList);

                    FriendListAdapter adapter = new FriendListAdapter(friendBeanList);

                    GlobalAssistMap.putObject("friendListAdapter", adapter);

                    if (friendBeanList.size() == 0) return true;

                    CompletableFuture.runAsync(() -> {

                        for (int i = 0; i < (Math.min(friendBeanList.size(), 20)); i++) {
                            GlobalAssistMap.putObject(friendBeanList.get(i).getId() + "Info", friendBeanList.get(i));
                        }

                    });


                    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
                    friend_recycler_view.setLayoutManager(linearLayoutManager);
                    adapterAddListener(adapter);
                    friend_recycler_view.setAdapter(adapter);

                    return true;
                }
            }), userId);
        } else {

            FriendListAdapter adapter = (FriendListAdapter) GlobalAssistMap.getObject("friendListAdapter");
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
            friend_recycler_view.setLayoutManager(linearLayoutManager);
            if (adapter == null) {
                adapter = new FriendListAdapter(friendBeanList);
                GlobalAssistMap.putObject("friendListAdapter", adapter);
            }
            adapterAddListener(adapter);
            friend_recycler_view.setAdapter(adapter);
        }

    }


    public void adapterAddListener(FriendListAdapter friendListAdapter) {

        if (friendListAdapter == null) {
            return;
        }

        friendListAdapter.setFriendItemOnClickListener(new FriendItemOnClickInterface() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onItemClick(RecyclerView parent, View view, int position, UserInfoBean userInfoBean) {

                String myId = (String) GlobalAssistMap.getObject("userId");
                String roomName = (Integer.parseInt(myId) + userInfoBean.getId()) + "chatroom";
                ServerOperation.connectChatRoom(roomName);

                Intent intent = new Intent();
                intent.setClass(getContext(), OneToOneChatActivity.class);
                intent.putExtra("friendName", userInfoBean.getNickname());
                intent.putExtra("friendId", userInfoBean.getId());
                intent.putExtra("onlineStatus", userInfoBean.getOnlineStatus());
                startActivity(intent);

            }
        });
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {

            if (resultCode == UPDATE_Friend_CODE) {
                LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
                friend_recycler_view.setLayoutManager(linearLayoutManager);
                FriendListAdapter adapter = (FriendListAdapter) GlobalAssistMap.getObject("friendListAdapter");
                adapterAddListener(adapter);
                friend_recycler_view.setAdapter(adapter);
            }

        }
    }
}
